package com.demo.config;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import com.demo.core.jdbc.mybatis.plugin.PerformanceInterceptor;
import com.demo.util.PropertiesUtils;
import com.demo.util.ResourceUtils;
import com.github.pagehelper.PageHelper;
import com.thetransactioncompany.util.PropertyParseException;
import com.thetransactioncompany.util.PropertyRetriever;

@Configuration
@Import({ AppDataSource.class })
public class AppConfigMybatis {

	// ---------------------------------------
	// bean
	// ---------------------------------------
	// masterDataSource

	@Bean
	@Autowired
	public SqlSessionFactoryBean sqlSessionFactory(@Qualifier("masterDataSource") DataSource ds,
			@Qualifier("jdbcPr") PropertyRetriever pr) throws IOException, PropertyParseException {
		SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
		factory.setDataSource(ds);
		factory.setMapperLocations(ResourceUtils.getResources("classpath:com/demo/mapping/*Mapper.xml"));
		factory.setTypeAliasesPackage("com.demo.*.domain");

		List<Interceptor> plugins = new ArrayList<>();
		plugins.add(pageHelperInterceptor());// 分页插件
		if (pr.getOptBoolean("debug", false)) {
			plugins.add(performanceInterceptor());// 性能插件
		}
		factory.setPlugins(plugins.toArray(new Interceptor[plugins.size()]));
		return factory;
	}

	@Bean
	public PerformanceInterceptor performanceInterceptor() throws IOException {
		PerformanceInterceptor inter = new PerformanceInterceptor();
		inter.setSlowSqlMillis(1000L);
		return inter;
	}

	@Bean
	public MapperScannerConfigurer mapperScannerConfigurer() throws IOException {
		MapperScannerConfigurer scan = new MapperScannerConfigurer();
		scan.setBasePackage("com.demo.mapper");
		Properties p = PropertiesUtils.loadProperties("mappers=tk.mybatis.mapper.common.Mapper");
		scan.setProperties(p);
		return scan;
	}

	@Bean
	public PageHelper pageHelperInterceptor() throws IOException {
		PageHelper inter = new PageHelper();
		Properties p = PropertiesUtils.loadProperties("dialect=mysql");
		inter.setProperties(p);
		return inter;
	}
}
